package com.aiphome.service;

import com.aiphome.model.AiService;
import com.aiphome.repository.AiServiceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class AiServiceService {

    @Autowired
    private AiServiceRepository aiServiceRepository;

    // 基本CRUD操作
    @Transactional
    public AiService createService(AiService aiService) {
        return aiServiceRepository.save(aiService);
    }

    @Transactional(readOnly = true)
    public Optional<AiService> getServiceById(Long id) {
        return aiServiceRepository.findById(id);
    }

    @Transactional(readOnly = true)
    public List<AiService> getAllServices() {
        return aiServiceRepository.findAll();
    }

    @Transactional
    public AiService updateService(AiService aiService) {
        return aiServiceRepository.save(aiService);
    }

    @Transactional
    public void deleteService(Long id) {
        aiServiceRepository.deleteById(id);
    }

    // 分页查询
    @Transactional(readOnly = true)
    public Page<AiService> getServicesWithPagination(int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return aiServiceRepository.findAll(pageable);
    }

    // 条件查询示例
    @Transactional(readOnly = true)
    public List<AiService> getActiveServicesByType(String serviceType) {
        Specification<AiService> spec = (root, query, criteriaBuilder) -> {
            return criteriaBuilder.and(
                    criteriaBuilder.equal(root.get("active"), true),
                    criteriaBuilder.equal(root.get("serviceType"), serviceType)
            );
        };
        return aiServiceRepository.findAll(spec);
    }

    // 高级查询：按准确度排序的服务
    @Transactional(readOnly = true)
    public List<AiService> getTopServicesByAccuracy(int limit) {
        return aiServiceRepository.findAll(
                PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "accuracyRate"))
        ).getContent();
    }

    // 批量操作示例
    @Transactional
    public List<AiService> batchCreateServices(List<AiService> services) {
        return aiServiceRepository.saveAll(services);
    }

    // 自定义事务边界示例
    @Transactional(rollbackFor = Exception.class)
    public void updateServiceStatus(Long id, boolean active) {
        AiService service = aiServiceRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Service not found"));
        service.setActive(active);
        aiServiceRepository.save(service);
        // 如果这里发生异常，事务会回滚
    }
}